package com.vieewer.btdemo.view.wifi;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.*;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.vieewer.btdemo.app.App;
import com.vieewer.btdemo.bean.*;
import com.vieewer.btdemo.utils.*;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static android.content.Context.WIFI_P2P_SERVICE;


/**
 * 官方文档
 * https://developer.android.com/guide/topics/connectivity/wifip2p.html
 * https://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html
 */
public class TransferPhotosManager {


    private List peers = new ArrayList();
    public static List<HashMap<String, String>> peersshow = new ArrayList();

    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    private WifiP2pInfo info;

    private FileServerAsyncTask mServerTask;
    private DataServerAsyncTask mDataTask;

    public  static String peerAddress = null;
    public  static String mineIp = null;
    public static List<String> paths = new ArrayList<>();

    public static List<String> clientName = new ArrayList<>();
    public static List<String> clientIp = new ArrayList<>();

    private static FileTransferRunnable mTransferRunnable;
    //     Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };


     String ipAddress = "";
     int port = 0;

    private SocketManager socketManager;
    public static Handler mHandler;

    public static final int MSG_SET_STATUS = 1;
    public static final int MSG_RECEIVE_FILE = 2;
    public static final int MSG_SEND_FILE = 3;
    public static final int MSG_SOC_CLOSED = 4;

    private String mIp = "";
    private Context mContext;


    private TransferPhotosManager() {

    }

    private static class Instance {
        public static TransferPhotosManager singletonState = new TransferPhotosManager();
    }

    public static TransferPhotosManager getNewInstance() {
        return Instance.singletonState;
    }



    public void init(Context ctx) {

       mContext = ctx;
       //EventBus.getDefault().register(this);

       initWritePermission();
       initIntentFilter();
       initReceiver();

       mHandler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               switch(msg.what){
                   case 0:
                       SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
                       break;
                   case 1:
//                        tvMsg.setText("本机IP：" + getIpAddress(TransferPhotosActivity.this) + " 监听端口:" + msg.obj.toString());
                       break;
                   case 2:
                       Toast.makeText(App.Companion.getInstance(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                       break;
               }
           }
       };


       socketManager = new SocketManager(mHandler);
   }


    //处理事件逻辑
/*    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventBus(MessageEvent messageEvent) {
        mIp = messageEvent.msg;
        Log.i("yjj", "receive msg from phone ~~~" + "ip = " + mIp + ", type =" + messageEvent.name);
        if (messageEvent.name.equals("连接")) {
            connect();
        } else if (messageEvent.name.equals("发送")) {
            //todo /DCIM/CAMERA 是否有照片
            String strpath="/storage/emulated/0/DCIM/Camera/";
            if (FileUtils.isExistFile(strpath)) {
                sendPhotos();
            } else {
                sendEmptyPhotoMsgToPhone();
            }

        } else if (messageEvent.name.equals("搜索")) {
            DiscoverPeers();
            Toast.makeText(App.Companion.getInstance(), "搜索开启", Toast.LENGTH_SHORT).show();
        }

    }*/

    private void sendEmptyPhotoMsgToPhone() {
        SwitchMsgBean data = new SwitchMsgBean();
        data.type = "EmptyPhoto";
        String dataStr = JSON.toJSONString(data);
        LogUtil.e("yjj", "sendEmptyPhotoMsgToPhone  ~~~");
        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);
    }



    public void handleEvent(MessageEvent messageEvent) {

        mIp = messageEvent.msg;
        Log.i("yjj", "receive msg from phone ~~~" + "ip = " + mIp + ", type =" + messageEvent.name);
        if (messageEvent.name.equals("连接")) {
            connect();
        } else if (messageEvent.name.equals("发送")) {
            //todo /DCIM/CAMERA 是否有照片
            String strpath="/storage/emulated/0/DCIM/Camera/";
            if (FileUtils.isExistFile(strpath)) {
                sendPhotos();
            } else {
                sendEmptyPhotoMsgToPhone();
            }
        } else if (messageEvent.name.equals("搜索")) {
            register();
            DiscoverPeers();
            Toast.makeText(App.Companion.getInstance(), "搜索开启", Toast.LENGTH_SHORT).show();
        }

    }


    private void sendPhotos() {

        ipAddress = mIp;
        port=9999;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            final ArrayList<String> fileNames = new ArrayList<>();
            final ArrayList<String> paths = new ArrayList<>();
            String strpath="/storage/emulated/0/DCIM/Camera/";
            File file = new File(strpath);
            List<File> fileList = CommonUtils.getFile(file);
            if (fileList != null && fileList.size() > 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    File file1 = fileList.get(i);
                    fileNames.add(fileList.get(i).getName());
                    paths.add(fileList.get(i).getPath());
                    Log.i("yjj文件名字", fileList.get(i).getName());
                }
                Log.i("yjj", "正在发送至" + ipAddress + ":" +  port);

                Thread sendThread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        socketManager.SendFile(fileNames, paths, ipAddress, port, mContext);
                    }
                });
                sendThread.start();

            }

        } else {

        }


    }



    private void connect() {
        if (peersshow.size() > 0) {
            CreateConnect(peersshow.get(0).get("address"),
                    peersshow.get(0).get("name"));
        }
    }


    /**
     * Android 6.0 需要手动检测读写权限（华为）
     */
    // Check if we have write permission
    private void initWritePermission(){
        int permission = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    (Activity) mContext,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }



    private void StopConnect() {

        mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.i("yjj","断开成功");
//                Toast.makeText(TransferPhotosActivity.this,"断开成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reason) {
                Log.i("yjj","断开失败");
//                Toast.makeText(TransferPhotosActivity.this,"断开失败",Toast.LENGTH_SHORT).show();

            }
        });
    }

    /*A demo base on API which you can connect android device by wifidirect,
    and you can send file or data by socket,what is the most important is that you can set
    which device is the client or service.*/

    private void CreateConnect(String address, final String name) {
        WifiP2pDevice device;
        WifiP2pConfig config = new WifiP2pConfig();
        Log.i("yjj", "获取到的mac："+address);


        config.deviceAddress = address;
        /*mac地址*/

        config.wps.setup = WpsInfo.PBC;

        mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
            //   Register for WIFI_P2P_CONNECTION_CHANGED_ACTION
            @Override
            public void onSuccess() {
                Toast.makeText(mContext,"连接成功！",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reason) {
                Toast.makeText(mContext,"连接失败！",Toast.LENGTH_SHORT).show();
            }
        });
    }




    private void initReceiver() {
        mManager = (WifiP2pManager) mContext.getSystemService(WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(mContext, Looper.myLooper(), null);

        WifiP2pManager.PeerListListener mPeerListListerner = new WifiP2pManager.PeerListListener() {
            @Override
            public void onPeersAvailable(WifiP2pDeviceList peersList) {
                peers.clear();
                peersshow.clear();
                Collection<WifiP2pDevice> aList = peersList.getDeviceList();
                peers.addAll(aList);

                for (int i = 0; i < aList.size(); i++) {
                    WifiP2pDevice a = (WifiP2pDevice) peers.get(i);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("name", a.deviceName);
                    map.put("address", a.deviceAddress);
                    peersshow.add(map);
                }
                //搜索成功 传给手机端可以发起连接
                Log.i("yjj","success 把搜索结果传给手机端");
                SearchSuccessBean resultBean = new SearchSuccessBean();
                resultBean.isSearchFinished = true;
                CommunicateToPhoneHelper.Companion.getInstance().write(JSON.toJSONString(resultBean));

                mContext.unregisterReceiver(mReceiver);

            }




        };

        WifiP2pManager.ConnectionInfoListener mInfoListener = new WifiP2pManager.ConnectionInfoListener() {

            @Override
            public void onConnectionInfoAvailable(final WifiP2pInfo minfo) {

                //清空设备列表信息
                peersshow.clear();

                Log.i("yjj", "InfoAvailable is on");
                info = minfo;

                Log.i("yjj", "groupOwnerAddress:"+info.groupOwnerAddress.getHostAddress());
                mineIp=info.groupOwnerAddress.getHostAddress();

                Log.i("yjj", "TransferPhotosActivity peerAddress:"+peerAddress);

                if (info.groupFormed && info.isGroupOwner) {
                    Log.i("yjj","Test:"+peerAddress);
//                  if(null == peerAddress){
                        mDataTask = new DataServerAsyncTask(mContext);
                        mDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        Log.i("yjj", "111 " );
//                  }
                    mServerTask = new FileServerAsyncTask(mContext);
                    mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    Log.i("yjj", "222 " );

                } else if (info.groupFormed) {
                    Log.i("yjj","Test:"+peerAddress);
                    if(peerAddress == null){
                        Log.i("yjj", "333 " );
                        Intent serviceIntent = new Intent(mContext,
                                DataTransferService.class);

                        serviceIntent.setAction(DataTransferService.ACTION_SEND_FILE);

                        serviceIntent.putExtra(DataTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
                                info.groupOwnerAddress.getHostAddress());
                        Log.i("yjj", "GroupOwnerIpIP is :" + info.groupOwnerAddress.getHostAddress());
                        serviceIntent.putExtra(DataTransferService.EXTRAS_GROUP_OWNER_PORT,
                                8887);
                        mContext.startService(serviceIntent);
                        Toast.makeText(mContext, "WiFi Connection success", Toast.LENGTH_SHORT).show();
                        peerAddress = CommonUtils.getIpAddress(mContext);
                        Log.i("yjj","修改后的peerAddress："+peerAddress);
                    }
                    Log.i("yjj", "444 " );
                    mServerTask = new FileServerAsyncTask(mContext);
                    mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

                }
            }

        };
        mReceiver = new WifiDirectBroadcastReceiver(mManager, mChannel, mPeerListListerner, mInfoListener);
    }



    private void DiscoverPeers() {
        mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            //Register for WIFI_P2P_PEERS_CHANGED_ACTION
            @Override
            public void onSuccess() {
            }

            @Override
            public void onFailure(int reason) {
            }
        });
    }

    private void initIntentFilter() {
        mFilter = new IntentFilter();
        mFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    }


    public void register() {
        mContext.registerReceiver(mReceiver, mFilter);
    }

    public void unregisterAndStop() {
        mHandler.removeCallbacksAndMessages(null);
        stopConnect();
    }

    public void stopConnect() {
        StopConnect();
    }

/*
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        StopConnect();
    }

    @Override
    public void onBackPressed() {
		super.onBackPressed();

    }
*/

}
